<template>
    <div>
      <el-table
        :data="messageList"
        style="width: 100%;height: 100%"
        :show-header="false"
        @row-click="toChat">
        <el-table-column style="width: 60px;height: 80px">
          <template slot-scope="scope">
            <el-form :model="scope.row" :inline="true" style="height: 80px" >
              <el-form-item>
                <div style="height: 80px;width: 50px">
                  {{scope.row.name}}
                  <el-avatar :src="scope.row.imageUrl"></el-avatar>
                </div>
              </el-form-item>
              <el-form-item>
                <el-button type="info" round class="message">{{scope.row.content}}</el-button>
              </el-form-item>
            </el-form>
          </template>
        </el-table-column>
      </el-table>
    </div>
</template>
<script>
import { findMessageList, findNewMessage, findUser } from '@/api/broker/broker'
export default {
  name: 'Index',
  data() {
    return {
      socket: {
        lockReconnect: false, // 是否真正建立连接
        timeout: 58 * 1000, // 58秒一次心跳
        timeoutObj: null, // 心跳心跳倒计时
        serverTimeoutObj: null, // 心跳倒计时
        timeoutnum: null // 断开 重连倒计时
      },
      messageList: [],
      messageRecordList: [],
      // 消息传输对象
      messageResult: {
        toUserId: null,
        toUserRole: null,
        images: null
      },
      user: {
        id: null,
        roleId: null,
        username: null,
        name: null
      }
    }
  },
  created() {
    this.findList()
    this.initWebSocket()
  },
  methods: {
    currentTime() {
      setInterval(this.formatDate, 500)
    },
    initWebSocket() {
      // 初始化weosocket
      findUser().then(res => {
        this.user = res.data
        this.user.username = this.user.id + '$' + this.user.roleId
        const wsUrl = 'ws://localhost:9216/webSocket/' + this.user.username
        if ('WebSocket' in window) {
          this.websocket = new WebSocket(wsUrl)
          // 客户端接收服务端数据时触发
          this.websocket.onmessage = this.websocketonmessage
          // 连接建立时触发
          this.websocket.onopen = this.websocketonopen
          // 通信发生错误时触发
          this.websocket.onerror = this.websocketonerror
          // 连接关闭时触发
          this.websocket.onclose = this.websocketclose
        } else {
          console.log('当前浏览器不支持webSocket')
        }
      })
    },
    // 连接建立时触发
    websocketonopen() {
      // 开启心跳
      this.start()
      // 连接建立之后执行send方法发送数据
      // let actions = {"room":"007854ce7b93476487c7ca8826d17eba","info":"1121212"};
      // this.websocketsend(JSON.stringify(actions));
    },
    // 通信发生错误时触发
    websocketonerror() {
      console.log('出现错误')
      this.reconnect()
    },
    // 客户端接收服务端数据时触发
    websocketonmessage(e) {
      console.log(e.data)
      this.findList()
      // 收到服务器信息，心跳重置
      this.reset()
    },
    websocketsend(Data) {
      // 数据发送
      this.websocket.send(Data)
    },
    // 连接关闭时触发
    websocketclose(e) {
      // 关闭
      console.log('断开连接', e)
      // 重连
      this.reconnect()
    },
    reconnect() {
      // 重新连接
      var that = this
      if (that.lockReconnect) {
        return
      }
      that.lockReconnect = true
      // 没连接上会一直重连，设置延迟避免请求过多
      that.timeoutnum && clearTimeout(that.timeoutnum)
      that.timeoutnum = setTimeout(function() {
        // 新连接
        that.initWebSocket()
        that.lockReconnect = false
      }, 5000)
    },
    reset() {
      // 重置心跳
      var that = this.socket
      // 清除时间
      clearTimeout(that.timeoutObj)
      clearTimeout(that.serverTimeoutObj)
      // 重启心跳
      that.start()
    },
    start() {
      // 开启心跳
      console.log('开启心跳')
      var self = this.socket
      self.timeoutObj && clearTimeout(self.timeoutObj)
      self.serverTimeoutObj && clearTimeout(self.serverTimeoutObj)
      self.timeoutObj = setTimeout(function() {
        // 这里发送一个心跳，后端收到后，返回一个心跳消息，
        if (this.websocket.readyState === 1) {
          // 如果连接正常
          // self.ws.send("heartCheck"); //这里可以自己跟后端约定
        } else {
          // 否则重连
          this.reconnect()
        }
        self.serverTimeoutObj = setTimeout(function() {
          // 超时关闭
          self.websocket.close()
        }, self.timeout)
      }, self.timeout)
    },
    toChat(val) {
      this.messageResult.toUserId = val.fromUserId
      this.messageResult.toUserRole = val.fromUserRole
      this.messageResult.images = val.imageUrl
      findNewMessage(this.messageResult).then(res => {
        this.messageRecordList = res.data
        this.$router.push({
          path: '/broker/messageList',
          query: {
            information: val,
            messageRecordList: this.messageRecordList
          }
        })
      })
    },
    findList() {
      findMessageList().then(res => {
        this.messageList = res.data
        console.log(this.messageList)
      })
    }
  },
  mounted() {
    this.currentTime()
  },
  // 销毁定时器
  beforeDestroy() {
    if (this.formatDate) {
      clearInterval(this.formatDate) // 在Vue实例销毁前，清除时间定时器
    }
  }
}
</script>
<style scoped>
</style>
